using System.ServiceModel;
using Nakio.Framework.Communication;
using Nakio.Framework.Exceptions;

namespace Nakio.Framework.Client
{
    public class MainClient
    {
        private readonly ServerContractClient _client;
        private readonly ClientCallback _clientCallback;

        public MainClient(string username, string password)
        {
            _clientCallback = new ClientCallback(); ;
            var context = new InstanceContext(_clientCallback);
            _client = new ServerContractClient(context);

            _clientCallback.EncryptToken = _client.LogClient(username, password);
        }

        public MainClient()
        {
            var context = new InstanceContext(new ClientCallback());
            _client = new ServerContractClient(context);
        }

        public void LogIn(string username, string password)
        {
            _clientCallback.EncryptToken = _client.LogClient(username, password);
        }

        public void LogOff()
        {
            _client.LogOffClient();
        }

        public void ExecuteCommandOnServer(CommandBase command)
        {
            if (_clientCallback.EncryptToken == null)
            {
                throw new ClientNotLoggedInException();
            }

            var encryptedCommand = new Communication.EncryptedCommand(_clientCallback.EncryptToken, command);
            _client.ExecuteCommand(encryptedCommand);
        }

        public T ExecuteCommandOnServer<T>(CommandBase command)
        {
            if (_clientCallback.EncryptToken == null)
            {
                throw new ClientNotLoggedInException();
            }

            var encryptedCommand = new Communication.EncryptedCommand(_clientCallback.EncryptToken, command);
            return (T) _client.ExecuteReturnCommand(encryptedCommand);
        }
    }
}